// import {login, getInfo} from 'api/user'
import {getToken, setToken, removeToken} from '../../utils/auth'
import {resetRouter} from '@/router'
// import router from '@/router'

const LOGIN = 'LOGIN'// 获取用户信息(登录)
const SetUserData = 'SetUserData'// 获取用户信息
const LOGOUT = 'LOGOUT'// 退出登录、清除用户数据
const USER_DATA = 'userDate'// 用户数据
const BIKE_CHANGE= 'BIKE_CHANGE'//修改用户借车的状态与车辆编号

export default {
    namespaced: true,
    state: {
        token: getToken() || '',
        user: JSON.parse(localStorage.getItem(USER_DATA) || null)
    },
    mutations: {
       // 获取用户信息(登录token)
        [LOGIN](state, data) {
            let userToken = data.data.token;
            state.token = userToken;
            setToken(userToken)
        },
       // 获取用户信息
        [SetUserData](state, userData = {}) {
            state.user = userData;
            localStorage.setItem(USER_DATA, JSON.stringify(userData))
        },
        // 退出登录、清除用户数据
        [LOGOUT](state) {
            state.user = null;
            state.token = null;
            removeToken();
            localStorage.removeItem(USER_DATA);
            resetRouter()
        },
        [BIKE_CHANGE](state,bikechange={}){
            state.user.borrowStatus = bikechange.borrowStatus;
            state.user.bicycleNum = bikechange.bicycleNum;
            let userData = state.user;
            localStorage.setItem(USER_DATA, JSON.stringify(userData))
        }

    },
    actions: {
        // 异步
        //
        // async login(state, data) {
        //     try {
        //         let res = await login({
        //             phoneNumber: data.phoneNumber,
        //             password: data.password
        //         });
        //         state.commit(LOGIN, res);
        //         console.log('登录成功');
        //         setTimeout(() => {
        //             const redirect = data.$route.query.redirect || '/'
        //             data.$router.replace({
        //                 path: redirect
        //             })
        //         }, 1500)
        //     } catch (error) {
        //         console.error(error)
        //     }
        // },
        // // get user info
        // // 获取用户信息
        // getInfo({commit, state}) {
        //     return new Promise((resolve, reject) => {
        //         getInfo(state.token).then(response => {
        //             const {data} = response

        //             if (!data) {
        //                 // eslint-disable-next-line
        //                 reject('Verification failed, please Login again.')// 验证失败，请重新登录。
        //             }
        //             commit(SetUserData, data)
        //             resolve(data)
        //         }).catch(error => {
        //             reject(error)
        //         })
        //     })
        // }
    },
    getters: {
        token(state) {
            return state.token
        },
        user(state) {
            return state.user
        }
    }
}
